package com.stylefeng.guns.crawlers.zgzc;

import cn.wanghaomiao.seimi.annotation.Crawler;
import cn.wanghaomiao.seimi.struct.Request;
import cn.wanghaomiao.seimi.struct.Response;
import com.stylefeng.guns.common.persistence.model.Game;
import lombok.extern.slf4j.Slf4j;
import org.jsoup.nodes.Element;
import org.seimicrawler.xpath.JXDocument;
import org.seimicrawler.xpath.JXNode;
import org.springframework.scheduling.annotation.Scheduled;

import java.util.List;

/**
 * 其他联赛爬虫
 *
 * @author wuchong
 */
@Crawler(name = "otherCrawler")
@Slf4j
public class OtherCrawler extends BaseZgcpCrawler {

    private static final long serialVersionUID = -6789561557459283755L;

    /**
     * @return 设置起始url
     */
    @Override
    public String[] startUrls() {
        return new String[]{"http://live.zgzcw.com/qb/"};
    }

    /**
     * 针对startUrl生成首批的response回调这个初始接口
     *
     * @param response --
     */
    @Override
    public void start(Response response) {

        JXDocument jxDocument = response.document();
        // 所有比赛列表
        List<JXNode> matchTrs = jxDocument.selN("//table[@id='matchTable']//tr[@class='matchTr']");
        List<String> mids = getMids();
        for (JXNode jxNode : matchTrs) {
            Element element = jxNode.asElement();
            // 将tr数据转换为北单比赛内容
            String mid = element.attr("matchid");
            if (mids.contains(mid)) {
                continue;
            }
            String title = element.getElementsByClass("matchType").get(0)
                    .getElementsByTag("span").text();
            int status = Integer.parseInt(element.getElementsByClass("matchDate").attr("status"));
            if (isLeague(title) && status == 0 || status == -1) {
                String expire = "1";
                if (status == -1) {
                    expire = "0";
                }
                String zhud = element.getElementsByClass("sptr").get(0).getElementsByTag("a")
                        .text();
                String ked = element.getElementsByClass("sptl").get(0).getElementsByTag("a")
                        .text();
                String time = element.getElementsByClass("matchDate").attr("date");

                //实际比分
                String actualScore = element.getElementsByClass("boldbf").get(1).text();

                Game game = Game.builder().mid(mid).zhud(zhud).ked(ked).title(title)
                        .expire(expire).actualScore(actualScore).time(time).build();
                game.setType(1);

                // 分析数据
                parseAnalysis(game);

            } else {
                log.warn("该场比赛={}不是联赛", mid);
            }
        }
    }

    @Scheduled(cron = "0 30 */2 * * ?")
    public void callByCron() {
        logger.info("我是一个根据cron表达式执行的调度器，1小时一次");
        // 可定时发送一个Request
        push(Request.build(startUrls()[0], "start").setSkipDuplicateFilter(true));
    }

}
